<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <!-- 询单基本信息显示 -->
        <a-card title="询单基本信息" size="small" style="margin-bottom: 16px">
          <a-descriptions :column="3" size="small">
            <a-descriptions-item label="客户名称">{{ model.customerName }}</a-descriptions-item>
            <a-descriptions-item label="客户电话">{{ model.customerPhone }}</a-descriptions-item>
            <a-descriptions-item label="门类型">
              <a-tag :color="model.type === 0 ? 'blue' : 'green'">
                {{ model.type === 0 ? '推拉' : '平开' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="收货地址" :span="2">{{ model.deliveryAddress }}</a-descriptions-item>
            <a-descriptions-item label="物流信息">
              <a-tag :color="model.logisticsType === 0 ? 'orange' : 'purple'">
                {{ model.logisticsType === 0 ? '到付' : '寄付' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="总价" :span="2">
              <span style="color: #f5222d; font-weight: bold; font-size: 16px">
                ¥{{ (model.totalPrice || 0).toFixed(2) }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="状态">
              <a-tag :color="getStatusColor(model.status)">
                {{ getStatusText(model.status) }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 询单规则配置 -->
        <a-card title="询单规则配置" size="small">
          <!-- 动态规则表单 -->
          <div v-if="inquiryRules.length > 0">
            <a-form-model-item
              v-for="rule in inquiryRules"
              :key="rule.id"
              :label="rule.name"
              :prop="`ruleValues.${rule.id}`"
              :rules="rule.isMust === 1 ? [{ required: true, message: `请选择或输入${rule.name}` }] : []"
            >
              <a-row :gutter="8">
                <a-col :span="12">
                  <a-select
                    v-model="model.ruleValues[rule.id]"
                    placeholder="请选择规则值"
                    allowClear
                    :disabled="isViewMode"
                    @change="(value) => handleRuleValueChange(rule, value)"
                  >
                    <a-select-option
                      v-for="(value, index) in rule.values"
                      :key="`${rule.id}-${index}`"
                      :value="value.value"
                    >
                      {{ value.value }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="12">
                  <a-input
                    v-model="model.ruleValues[rule.id]"
                    placeholder="或手动输入"
                    :disabled="isViewMode"
                    @input="(e) => handleManualInput(rule, e.target.value)"
                  />
                </a-col>
              </a-row>
            </a-form-model-item>
          </div>

          <a-empty v-else-if="model.type !== undefined" description="暂无询单规则，请先配置询单规则" />
        </a-card>
      </a-form-model>
    </a-spin>

    <!-- 自定义底部按钮 -->
    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button v-if="!isViewMode" type="primary" :loading="confirmLoading" @click="handleOk"> 确定 </a-button>
    </template>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'

export default {
  name: 'InquiryItemModal',
  components: {},
  data() {
    return {
      title: '询单明细',
      visible: false,
      isViewMode: false, // 是否为查看模式
      model: {
        type: 0,
        ruleValues: {},
        totalPrice: 0,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        type: [{ required: true, message: '请选择门类型!', trigger: 'change' }],
      },
      url: {
        edit: '/oms/inquiry/edit',
        queryById: '/oms/inquiry/queryById',
      },
      inquiryRules: [],
    }
  },
  methods: {
    // 查看模式
    view(record) {
      this.isViewMode = true
      this.title = '询单明细 - 查看'
      this.loadInquiryData(record)
    },
    // 编辑模式
    edit(record) {
      this.isViewMode = false
      this.title = '询单明细 - 编辑'
      this.loadInquiryData(record)
    },
    // 加载询单数据
    loadInquiryData(record) {
      this.form.resetFields()
      this.model = Object.assign(
        {
          type: 0,
          ruleValues: {},
          totalPrice: 0,
        },
        record
      )

      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(this.model)
      })

      // 加载询单明细
      if (record.id) {
        this.loadInquiryDetails(record.id)
      }

      // 加载询单规则
      if (this.model.type !== undefined) {
        this.loadInquiryRules()
      }
    },
    // 加载询单明细数据
    loadInquiryDetails(inquiryId) {
      const that = this
      that.confirmLoading = true

      getAction(`${this.url.queryById}?id=${inquiryId}`)
        .then((res) => {
          if (res.success && res.result) {
            const inquiry = res.result
            that.model = Object.assign(that.model, inquiry)

            // 处理询单明细数据
            if (inquiry.items && inquiry.items.length > 0) {
              const ruleValues = {}
              inquiry.items.forEach((item) => {
                ruleValues[item.ruleId] = item.ruleValue
              })
              that.model.ruleValues = ruleValues
            }

            // 重新加载规则
            that.loadInquiryRules()
          } else {
            that.$message.warning(res.message || '加载询单详情失败')
          }
        })
        .catch((error) => {
          console.error('加载询单详情失败:', error)
          that.$message.error('加载询单详情失败')
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      if (this.isViewMode) {
        this.handleCancel()
        return
      }

      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true

          // 构建提交数据
          const submitData = {
            ...this.model,
            items: this.buildInquiryItems(),
          }

          httpAction(this.url.edit, submitData, 'put')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.visible = false
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleDoorTypeChange() {
      // 门类型改变时重新加载规则
      this.model.ruleValues = {}
      this.loadInquiryRules()
    },
    loadInquiryRules() {
      if (this.model.type === undefined) {
        this.inquiryRules = []
        return
      }

      const that = this
      that.confirmLoading = true

      // 加载询单规则
      httpAction('/oms/inquiry/rule/listByType?type=' + this.model.type, {}, 'get')
        .then((res) => {
          if (res.success) {
            that.inquiryRules = res.result || []

            // 为每个规则加载规则值
            const promises = that.inquiryRules.map((rule) => {
              return httpAction('/oms/omsInquiryRuleValue/listByRuleId?ruleId=' + rule.id, {}, 'get').then(
                (valueRes) => {
                  if (valueRes.success) {
                    // 使用Vue.set确保响应式更新
                    that.$set(rule, 'values', valueRes.result || [])
                    console.log(`规则 ${rule.name} 加载了 ${(valueRes.result && valueRes.result.length) || 0} 个值:`, valueRes.result)
                  } else {
                    console.warn(`规则 ${rule.name} 加载值失败:`, valueRes.message)
                    that.$set(rule, 'values', [])
                  }
                }
              ).catch((error) => {
                console.error(`规则 ${rule.name} 加载值异常:`, error)
                that.$set(rule, 'values', [])
              })
            })

            Promise.all(promises)
              .then(() => {
                // 规则加载完成后计算总价
                that.calculateTotalPrice()
              })
              .finally(() => {
                that.confirmLoading = false
              })
          } else {
            that.$message.warning(res.message)
            that.confirmLoading = false
          }
        })
        .catch(() => {
          that.confirmLoading = false
        })
    },
    handleRuleValueChange(rule, value) {
      this.$set(this.model.ruleValues, rule.id, value)
      this.calculateTotalPrice()
    },
    handleManualInput(rule, value) {
      this.$set(this.model.ruleValues, rule.id, value)
      this.calculateTotalPrice()
    },
    calculateTotalPrice() {
      try {
        // 查找总高、总宽、门单价规则
        let totalHeight = 0
        let totalWidth = 0
        let doorPrice = 0

        this.inquiryRules.forEach((rule) => {
          const ruleValue = this.model.ruleValues[rule.id]
          if (ruleValue) {
            const numValue = parseFloat(ruleValue)
            if (!isNaN(numValue)) {
              if (rule.name === '总高') {
                totalHeight = numValue
              } else if (rule.name === '总宽') {
                totalWidth = numValue
              } else if (rule.name === '门单价') {
                doorPrice = numValue
              }
            }
          }
        })

        // 计算总价：(总高*总宽)/1000*门单价
        if (totalHeight > 0 && totalWidth > 0 && doorPrice > 0) {
          this.model.totalPrice = (totalHeight / 1000) * (totalWidth / 1000) * doorPrice
        } else {
          this.model.totalPrice = 0
        }
      } catch (error) {
        console.error('计算总价失败:', error)
        this.model.totalPrice = 0
      }
    },
    buildInquiryItems() {
      const items = []
      this.inquiryRules.forEach((rule, index) => {
        const ruleValue = this.model.ruleValues[rule.id]
        if (ruleValue) {
          items.push({
            ruleId: rule.id,
            ruleName: rule.name,
            ruleValue: ruleValue,
            sortNo: rule.sortNo || index + 1,
          })
        }
      })
      return items
    },
    getStatusColor(status) {
      const statusMap = {
        0: 'orange',
        1: 'blue',
        2: 'green',
      }
      return statusMap[status] || 'default'
    },
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '已处理',
        2: '已完成',
      }
      return statusMap[status] || '未知'
    },
  },
}
</script>

<style scoped>
.ant-descriptions-item-label {
  font-weight: 600;
}
</style>
